//
//  LCPGetRongCloudToken.m
//  AFNetworkingTest
//
//  Created by lanou3g on 15/11/28.
//  Copyright © 2015年  All rights reserved.
//

#import "LCPGetRongCloudToken.h"
//生成Token
#define BASE_URL @"https://api.cn.rong.io/user/getToken.json"
//同步数组信息
#define SyncGroup_URl @"https://api.cn.ronghub.com/group/sync.json"
@implementation LCPGetRongCloudToken

static NSString *Signature = nil;

- (void)getTokenWithUserId:(NSString *)userId Name:(NSString *)name PortraitUri:(NSString *)portraitUri CallBack:(MyBlock)callBack{
    if (!_app_key || !_appSecret) {
        NSLog(@"请先设置appkey和appSecret");
        return;
    }
    NSDictionary *parameters = @{
                                 @"userId":userId,
                                 @"name":name,
                                 @"portraitUri":portraitUri,
                                 };
    __block NSString *token = nil;
    [self getNetDataWithParameter:parameters URL:BASE_URL CallBack:^(id data) {
        if (data == nil) {
            callBack(nil);
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                id parseData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
                token = parseData[@"token"];
                callBack(token);
            });
        }
    }];
}


// 同步用户群组
- (void)syncGroups:(NSString *)userId callBack:(MyBlock2)callback Group:(NSDictionary *)group , ...{
    if (!_app_key || !_appSecret) {
        NSLog(@"请先设置appkey和appSecret");
        return;
    }
    va_list ap;
    NSMutableDictionary *objDict = [NSMutableDictionary dictionary];
    [objDict setValue:userId forKey:@"userId"];
    va_start(ap, group);
    while (YES) {
        id obj = va_arg(ap, id);
        if (obj == nil)break;
        NSString *key = [NSString stringWithFormat:@"group[%@]",obj[@"gId"]];
        NSString *value = obj[@"gName"];
        [objDict setObject:value forKey:key];
    }
    va_end(ap);
    __block NSInteger result;
    [self getNetDataWithParameter:objDict URL:SyncGroup_URl CallBack:^(id token) {
        if (token == nil) {
            callback(0);
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                id parseData = [NSJSONSerialization JSONObjectWithData:token options:(NSJSONReadingAllowFragments) error:nil];
                result = [parseData[@"code"] integerValue];
                callback(result);
            });
        }
    }];
}

// 获取网络数据私有方法
- (void)getNetDataWithParameter:(NSDictionary *)params URL:(NSString *)url CallBack:(MyBlock)callBack{
    // 创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    // 设置请求方式
    [request setHTTPMethod:@"post"];
    // 设置请求参数
    NSData *tempData = [self httpBodyFromParamDictionary:params];
    [request setHTTPBody:tempData];
    NSString *appkey = self.app_key;
    NSString *nonce = [NSString stringWithFormat:@"%d", arc4random_uniform(10000)];
    NSString *Timestamp = [NSString stringWithFormat:@"%ld",time(NULL)];
    NSString *appSecret = self.appSecret;
    [request setValue:appkey forHTTPHeaderField:@"App-Key"];
    [request setValue:nonce forHTTPHeaderField:@"Nonce"];
    [request setValue:Timestamp forHTTPHeaderField:@"Timestamp"];
    [request setValue:appSecret forHTTPHeaderField:@"appSecret"];
    [request setValue:[self getSHA1String] forHTTPHeaderField:@"Signature"];
    // 创建session会话
    NSURLSession *session = [NSURLSession sharedSession];
    // 创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil) {
            callBack(nil);
        }else{
            callBack(data);
        }
    }];
    [task resume];
}

// 请求参数设置
- (NSData *)httpBodyFromParamDictionary:(NSDictionary *)params
{
    NSMutableString * data = [NSMutableString string];
    for (NSString * key in params.allKeys) {
        [data appendFormat:@"%@=%@&",key,params[key]];
    }
    return [[data substringToIndex:data.length-1] dataUsingEncoding:NSUTF8StringEncoding];
}


/**
 *  获取sha1哈希加密字符串
 *
 *  @return 哈希加密字符串
 */
- (NSString *)getSHA1String{
    if (self.appSecret) {
        NSString *str = [NSString stringWithFormat:@"%@%@%@",self.appSecret,[NSString stringWithFormat:@"%d",arc4random_uniform(10000)],[NSString stringWithFormat:@"%ld",time(NULL)]];
        CocoaSecurityResult *result_sha1 = [CocoaSecurity sha1:str];
        return result_sha1.hex;
    }else{
        NSLog(@"请设置appSecret");
        return nil;
    }
}

@end
